const { db } = require("../Schema/config");

//通过db对象创建操作文章表的模型对象
const ArticleSchema = require("../Schema/article");
const Article = db.model("articles", ArticleSchema);

//通过db对象创建操作用户表的模型对象
const UserSchema = require("../Schema/user");
const User = db.model("users", UserSchema);

//通过db对象创建操作评论表的模型对象
const CommentSchema = require("../Schema/comment");
const Comment = db.model("comments", CommentSchema);

//保存评论
exports.addComment = async (ctx, next) => {
  //验证用户是否登录
  let message = {
    status: 0,
    msg: "登录才能发表"
  };

  if (ctx.session.isNew) {
    return (ctx.body = message);
  }

  //用户已登录
  const data = ctx.request.body;
  //扩展当前用户的id值
  data.form = ctx.session.uid;

  const _comment = new Comment(data);

  await _comment
    .save()
    .then(data => {
      message = {
        status: 1,
        msg: "评论成功"
      };

      //更新当前文章评论的数量
    })
    .catch(err => {
      message = {
        status: 0,
        msg: err
      };
    });

    ctx.body = message;
};
